$(function() {
	if (window.errorMsg) {
		$("#alert-warning").append(window.errorMsg).removeClass("hidden")
				.hide().fadeIn("slow");
		$("#alert-warning").fadeOut(5000);
	}
	validationOption = {
		rules : {
			name : {
				required : true
			},
			province : {
				required : true
			},
			city : {
				required : true
			},
			district : {
				required : true
			},
			rate : {
				required : true
			}
		},
		messages : {
			name : {
				required : "请输入项目名称！"
			},
			province : {
				required : "请选择项目所在省份！"
			},
			city : {
				required : "请选择项目所在市！"
			},
			district : {
				required : "请选择项目所在区！"
			},
			rate : {
				required : "请输入项目费率！"
			}
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		unhighlight : function(element) {
			$(element).closest('.form-group').removeClass('has-error');
		},
		errorElement : 'span',
		errorClass : 'help-block',
		errorPlacement : function(error, element) {
			if (element.parent('.input-group').length) {
				error.insertAfter(element.parent());
			} else {
				error.insertAfter(element);
			}
		}

	};
	$('#addForm').validate(validationOption);
	$('#editForm').validate(validationOption);
	var table = $('#project')
			.DataTable(
					{
						"processing" : true,
						"serverSide" : true,
						"dom" : 'tr<"bottom"ip>',
						"ajax" : {
							"url" : window.basePath + "project/list",
							"type" : "POST",
						},
						"language" : {
							"zeroRecords" : "无数据！",
							"infoEmpty" : "没有找到该条记录！",
							"infoFiltered" : "(共 _MAX_ 条记录)",
							"processing" : "加载中...",
							"lengthMenu" : "_MENU_ Einträge anzeigen",
							"info" : "显示第_START_ 到第 _END_条记录 （共 _TOTAL_ 条记录）",
							"infoPostFix" : "",
							"paginate" : {
								"first" : "第一页",
								"previous" : "上一页",
								"next" : "下一页",
								"last" : "最后一页"
							}
						},
						"columns" : [
								{
									"data" : "name"
								},
								{
									"data" : "description"
								},
								{
									"data" : "province"
								},
								{
									"data" : "city"
								},
								{
									"data" : "district"
								},
								{
									"data" : "rate"
								},
								{
									"targets" : -1,
									"class" : "details-control",
									"orderable" : false,
									"data" : null,
									"searchable" : false,
									"defaultContent" : "<button type='button' class='btn btn-success btn-sm'>编辑</button>&nbsp;<button type='button' class='btn btn-danger btn-sm'>删除</button>"
								} ]

					});
	$.fn.dataTable.ext.errMode = 'throw';
	$("#searchName").on('keyup', function() {
		table.column(0).search(this.value).draw();
	});
	$("#searchProvince").on(
			'change',
			function() {
				if ($(this).get(0).selectedIndex != 0) {
					table.column(2).search(this.value).draw();
					$(this).parents('form').find('[name="city"]').html(
							"<option>请选择市</option>");
					loadCity($(this).val(), $(this).parents('form').find(
							'[name="city"]'));
					$(this).parents('form').find('[name="district"]').html(
							"<option>请选择区县</option>");
					$(this).parents('form').find('[name="district"]')
							.selectpicker('refresh');
				} else {
					table.column(2).search("").draw();
					$(this).parents('form').find('[name="city"]').html(
							"<option>请选择市</option>");
					$(this).parents('form').find('[name="city"]').selectpicker(
							'refresh');
					$(this).parents('form').find('[name="district"]').html(
							"<option>请选择区县</option>");
					$(this).parents('form').find('[name="district"]')
							.selectpicker('refresh');
				}
			});

	$("#searchCity").on(
			'change',
			function() {
				if ($(this).get(0).selectedIndex != 0) {
					table.column(3).search(this.value).draw();
					$(this).parents('form').find('[name="district"]').html(
							"<option>请选择区县</option>");
					loadDistrict($(this).parents('form').find(
							'[name="province"]').val(), $(this).val(), $(this)
							.parents('form').find('[name="district"]'));
				} else {
					table.column(3).search("").draw();
					$(this).parents('form').find('[name="district"]').html(
							"<option>请选择区县</option>");
					$(this).parents('form').find('[name="district"]')
							.selectpicker('refresh');
				}
			});

	$("#searchDistrict").on('change', function() {
		if ($(this).get(0).selectedIndex != 0) {
			table.column(4).search(this.value).draw();
		} else {
			table.column(4).search("").draw();
		}
	});

	$("#project tbody").on("click", "button", function() {
		var data = table.row($(this).parents('tr')).data();
		if ($(this).hasClass('btn-success')) {

			$("#nameEdit").val(data.name);
			$("#descriptionEdit").val(data.description);
			$("#provinceEdit").html("");
			$.ajax({
				url : window.basePath + "location/getProvince",
				type : 'POST',
				success : function(d) {
					for (var i = 0; i < d.length; i++) {
						var text = "<option>" + d[i] + "</option>";
						$("#provinceEdit").append(text);
					}
					$("#provinceEdit").val(data.province);
					$("#provinceEdit").selectpicker('refresh');
				}
			});
			$("#cityEdit").html("");
			$.ajax({
				url : window.basePath + "location/getCity",
				type : 'POST',
				data : {
					province : data.province
				},
				success : function(d) {
					for (var i = 0; i < d.length; i++) {
						var text = "<option>" + d[i] + "</option>";
						$("#cityEdit").append(text);
					}
					$("#cityEdit").val(data.city);
					$("#cityEdit").selectpicker('refresh');
				}
			});
			$("#districtEdit").html("");
			$.ajax({
				url : window.basePath + "location/getDistrict",
				type : 'POST',
				data : {
					province : data.province,
					city : data.city
				},
				success : function(d) {
					for (var i = 0; i < d.length; i++) {
						var text = "<option>" + d[i] + "</option>";
						$("#districtEdit").append(text);
					}
					$("#districtEdit").val(data.district);
					$("#districtEdit").selectpicker('refresh');
				}
			});
			$("#rateEdit").val(data.rate);
			$("#idEdit").val(data.id);
			$('#editProjectModal').modal('show');

		} else if ($(this).hasClass('btn-danger')) {
			$("#idDelete").val(data.id);
			$('#deleteProjectModal').modal('show');
		}

	});

	$("#addProject").click(function() {
		$("#createProjectModal").modal('show');
		loadProvince();
	});

	$('.selectpicker').selectpicker({
		style : 'btn',
		size : 8,
		showContent : false
	});

	function loadProvince() {
		$.ajax({
			url : window.basePath + "location/getProvince",
			type : 'POST',
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					var text = "<option>" + data[i] + "</option>";
					$("[name='province']").append(text);
				}
				$("[name='province']").selectpicker('refresh');
				loadCity(data[0], $("#city"));
			}
		});

	}
	
	$(".province").on(
			'change',
			function() {

				$(this).parents('form').find('[name="city"]').html("");
				loadCity($(this).val(), $(this).parents('form').find(
						'[name="city"]'));
				$(this).parents('form').find('[name="district"]').html("");
				$(this).parents('form').find('[name="district"]').selectpicker(
						'refresh');
			});

	$(".city").on(
			'change',
			function() {
				$(this).parents('form').find('[name="district"]').html("");
				loadDistrict($(this).parents('form').find('[name="province"]')
						.val(), $(this).val(), $(this).parents('form').find(
						'[name="district"]'));

			});

	function loadCity(province, dom) {
		$.ajax({
			url : window.basePath + "location/getCity",
			type : 'POST',
			data : {
				province : province
			},
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					var text = "<option>" + data[i] + "</option>";
					$(dom).append(text);
				}
				$(dom).selectpicker('refresh');
				loadDistrict(province, data[0], $(dom).parents('form').find(
						'[name="district"]'));
			},
			error : function() {
				alert(arguments[1]);
			}
		});
	}
	function loadDistrict(province, city, dom) {
		$.ajax({
			url : window.basePath + "location/getDistrict",
			type : 'POST',
			data : {
				province : province,
				city : city
			},
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					var text = "<option>" + data[i] + "</option>";
					$(dom).append(text);
				}
				$(dom).selectpicker('refresh');
			}
		});
	}
	$('#collapseOne').on(
			'show.bs.collapse',
			function() {
				$("#arrow").removeClass("glyphicon glyphicon-chevron-down")
						.addClass("glyphicon glyphicon-chevron-up");
			});
	$('#collapseOne').on(
			'hide.bs.collapse',
			function() {
				$("#arrow").removeClass("glyphicon glyphicon-chevron-up")
						.addClass("glyphicon glyphicon-chevron-down");
			});
});